package beanstao.util.json;

import java.util.ArrayList;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonBeanProcessor;
import net.sf.json.processors.PropertyNameProcessor;

import beanstao.util.collections.EnableEventCollection;

public class EnableCollectionJsonBeanProcessor implements JsonBeanProcessor
{

	public EnableCollectionJsonBeanProcessor(final JsonLibConfig configUtil)
	{
		_JsonConfigUtil = configUtil;
		_JsonConfig = new JsonConfig();
		// 设置要排除的属性
		_JsonConfig.setExcludes(configUtil.getExcludeNames());
		_JsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor());
		// this._JsonConfig.registerJsonBeanProcessor(EnableEventCollection.class, this);
	}

	private JsonConfig _JsonConfig = null;
	private JsonLibConfig _JsonConfigUtil = null;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public JSONObject processBean(Object arg0, JsonConfig arg1)
	{
		EnableEventCollection collection = (EnableEventCollection) arg0;
		ArrayList array = new ArrayList();
		for (int i = 0; i < collection.size(); i++)
			array.add(collection.get(i));
		// 设置改名输出
		PropertyNameProcessor propertyNameProcessor = new PropertyNameProcessor()
		{
			@Override
			public String processPropertyName(Class arg0, String arg1)
			{
				if (_JsonConfigUtil.getRenameMap().containsKey(arg1))
					return _JsonConfigUtil.getRenameMap().get(arg1);
				return arg1;
			}
		};
		_JsonConfig.registerJsonPropertyNameProcessor(java.util.ArrayList.class, propertyNameProcessor);
		String json = JSONArray.fromObject(array, _JsonConfig).toString();
		int length = json.length();
		json = json.substring(1, length - 1);
		return JSONObject.fromObject(json);
	}

}
